package cn.wowjoy.office.materialinspection.xunjian.task;

import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;

import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.ItemInspectRvDetailAdapter;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.SubmitPDARequest;
import cn.wowjoy.office.data.response.InspectTaskDtlVO;
import cn.wowjoy.office.data.response.InspectionTaskControllerResponse;
import cn.wowjoy.office.data.response.SingleTaskController;
import cn.wowjoy.office.data.response.SubmitPDAResponse;
import cn.wowjoy.office.homepage.MenuHelper;
import cn.wowjoy.office.utils.ToastUtil;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2017/11/1.
 */

public class PatrolTaskViewModel extends NewBaseViewModel{

   private MediatorLiveData<LiveDataWrapper<InspectionTaskControllerResponse>> response = new MediatorLiveData<>();
    private MediatorLiveData<Boolean> load = new MediatorLiveData<>();
    private MediatorLiveData<InspectTaskDtlVO> jump = new MediatorLiveData<>();
    private String taskId;
    private  String filter;

    public MediatorLiveData<InspectTaskDtlVO> getJump() {
        return jump;
    }

    public MediatorLiveData<Boolean> getLoad() {
        return load;
    }

    public MediatorLiveData<LiveDataWrapper<InspectionTaskControllerResponse>> getResponse() {
        return response;
    }

    public void jump(InspectTaskDtlVO inspectTaskDtlVO){
      jump.setValue(inspectTaskDtlVO);
    }

    @Override
    public void loadData(boolean ref) {
        super.loadData(ref);
       load.setValue(ref);
//       getInspectTaskControllerByPageSize(taskId,"","","","","",ref,filter);
//        mPatrolTaskActivity.setFilterText(mPatrolTaskActivity.filter.trim(),ref);
    }
    @Inject
    ApiService apiService;
    public SingleTaskController single;
    public ArrayList<InspectTaskDtlVO> datas;
    public ItemInspectRvDetailAdapter mItemRvDetailAdapter = new ItemInspectRvDetailAdapter();
    public LRecyclerViewAdapter wladapter = new LRecyclerViewAdapter(mItemRvDetailAdapter);

    @Inject
    public PatrolTaskViewModel(@NonNull NewMainApplication application) {
        super(application);
        mItemRvDetailAdapter.setItemEventHandler(this);
    }

    public void setWData(List<InspectTaskDtlVO> data) {
        if (null == datas)
            datas = new ArrayList<>();
        datas.clear();
        datas.addAll(data);
        mItemRvDetailAdapter.setData(datas);
        refreshComplete();
    }
    public void refreshData(boolean isRefresh ,List<InspectTaskDtlVO> data) {
        if (null == datas)
            datas = new ArrayList<>();
        datas.clear();
        datas.addAll(data);
        if (isRefresh) {
            mItemRvDetailAdapter.refresh(data);
        } else {
            mItemRvDetailAdapter.loadMore(data);
        }
        wladapter.removeFooterView();
        if (!isRefresh && (null == data || data.isEmpty() )){
            LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
            View view = inflater.inflate(R.layout.nodata_footview,null,false);
            wladapter.addFooterView(view);
        }
        wladapter.notifyDataSetChanged();
        refreshComplete();
    }

    @Override
    public void onCreateViewModel() {

    }
    private final int pageSize = 10;
    private int pageIndex = 0;
    public void getInspectTaskControllerByPageSize(String taskId,String billInfo,String isExist,String notInspect,String appAbNormal,String assetsStatus,boolean isRefresh,String filter){
        this.taskId = taskId;
        this.filter = filter;
        if (isRefresh){
            pageIndex = 0;
        } else {
            ++pageIndex;
        }
        response.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getInspectTaskControllerByPageSize(taskId,billInfo,isExist,notInspect,appAbNormal,assetsStatus,"","","","",pageIndex,pageSize)
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((InspectionTaskControllerResponse taskListResponse) -> {
                    //TODO: 设置界面上的详细数据 着重区分下！！！ 已完成和未完成显示的页面区别
                    response.setValue(LiveDataWrapper.success(taskListResponse));
                    this.single = taskListResponse.getSingle();
                     refreshData(isRefresh ,taskListResponse.getSingle().getDtlListPDA());
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        response.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }
    public void getInspectTaskControllerByPageSize(String taskId,String billInfo,String isExist,String notInspect,String appAbNormal,String assetsStatus
            ,String appearanceStatus,String labelStatus,String functionStatus,String cleanStatus, boolean isRefresh,String filter){
        this.taskId = taskId;
        this.filter = filter;
        if (isRefresh){
            pageIndex = 0;
        } else {
            ++pageIndex;
        }
        response.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getInspectTaskControllerByPageSize(taskId,billInfo,isExist,notInspect,appAbNormal,assetsStatus,appearanceStatus,labelStatus,functionStatus,cleanStatus,pageIndex,pageSize)
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((InspectionTaskControllerResponse taskListResponse) -> {
                    //TODO: 设置界面上的详细数据 着重区分下！！！ 已完成和未完成显示的页面区别
                    response.setValue(LiveDataWrapper.success(taskListResponse));
                    this.single = taskListResponse.getSingle();
                    refreshData(isRefresh ,taskListResponse.getSingle().getDtlListPDA());
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        response.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }
    public MediatorLiveData<LiveDataWrapper<Boolean>> submitPDA(String id , String inspectRecordId ,String useDepartmentId){
        final MediatorLiveData<LiveDataWrapper<Boolean>> submit = new MediatorLiveData<>();
        submit.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.submitPDA(new SubmitPDARequest(id,inspectRecordId,useDepartmentId), MenuHelper.getAuidS().get("zc_inspect"))
                .flatMap(new ResultDataParse<>())
                .compose(new RxSchedulerTransformer<>())
                .subscribe((SubmitPDAResponse submitPDAResponse) -> {
                    //TODO: 设置界面上的详细数据 着重区分下！！！ 已完成和未完成显示的页面区别
//                    if(null != waitDialog){
//                        CreateDialog.dismiss(mPatrolTaskActivity, waitDialog);
//                    }
                    ToastUtil.toastImage(getApplication().getApplicationContext(),"提交成功",-1);
                    submit.setValue(LiveDataWrapper.success(true));
                }, (Throwable throwable) -> {
                    submit.setValue(LiveDataWrapper.error(throwable,null));
//                    if (throwable instanceof ResultException && throwable.getMessage().equals("当前巡检任务尚未巡检完成,无法提交")){
//                        CreateDialog.submitDialog(mPatrolTaskActivity, "提交失败", "当前巡检任务还有设备未巡检,请巡检完成后提交");
//                    } else {
//                        mPatrolTaskActivity.handleException(throwable,false);
//                    }
                });
        addDisposable(disposable);
        return submit;
    }
}
